package com.dotdashdot.pocketquest;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Random;

import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;

import com.android.vending.billing.IInAppBillingService;

public class ClassAndroidBilling {
	String item_name;
	private ClassAndroidLogger logger;
	
	private static final char[] symbols = new char[36];

    static {
        for (int idx = 0; idx < 10; ++idx){
            symbols[idx] = (char) ('0' + idx);
        }
        for (int idx = 10; idx < 36; ++idx){
            symbols[idx] = (char) ('a' + idx - 10);
        }
    }
	
	ClassAndroidBilling(){
		logger = new ClassAndroidLogger("AndroidBilling");
	}
	
	public boolean submitPurchase(String item_name, int item_payload, IInAppBillingService  mService, MainActivity activity, final Object return_object, final Method return_method){
		
		logger.info("Item name: " + item_name);
		logger.info("Item payload: " + item_payload);
		
		activity.return_method = return_method;
		activity.return_object = return_object;
		
		this.item_name = item_name;
		
		ArrayList<String> skuList = new ArrayList<String> ();
		skuList.add(item_name);
		Bundle querySkus = new Bundle();
		querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
		
		RandomString randomString = new RandomString(36);
        //System.out.println("RandomString>>>>" + randomString.nextString());
        /* String payload = ""; */
        // bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ
        String payload = item_payload + ">>>" + randomString.nextString();
        Log.e("Random generated Payload", "payload: " + payload);
		
        //load_billing_task task = new load_billing_task(mService, activity, payload);
        
        activity.call_billing_task(mService, payload, item_name);
        
        /*load_billing_task task = new load_billing_task();
        task.payload = payload;
        Log.i("AndroidBilling","payload");
        task.mService = mService;
        Log.i("AndroidBilling","mservice");
        task.activity = activity;
        Log.i("AndroidBilling","activity");
		task.execute();*/
		
		return true;
	}
	
	public class RandomString{
		private final Random random = new Random();

        private final char[] buf;

        public RandomString(int length) {
            if (length < 1)
                throw new IllegalArgumentException("length < 1: " + length);
            buf = new char[length];
        }

        public String nextString() {
            for (int idx = 0; idx < buf.length; ++idx)
                buf[idx] = symbols[random.nextInt(symbols.length)];
            return new String(buf);
        }
	}
}
